package com.berte.uart;

import java.util.Queue;

import static java.lang.Thread.sleep;

/**
 * 串口接收线程，使用串口接收线程，将数据接收到uartRecvQueue中
 * 启动本线程前需要设置uart和uartRecvQueue。
 */
public class UartRecv implements Runnable {
    private Queue<Byte> uartRecvQueue = null;
    private Uart uart = null;
    public volatile boolean running = true;
    public volatile boolean isRunning = true;

    @Override
    public void run() {
        byte[] data;
        int ReadSize = 0;

        while (true) {
            if (running) {
                isRunning = true;
                ReadSize = uart.getInputBufferBytesCount();
                if (ReadSize != 0) {
                    data = uart.readBytes(ReadSize);
                    if (data != null) {
                        for (byte b : data) {
                            uartRecvQueue.offer(b);
                        }
                    }
                }

                try {
                    sleep(5);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                isRunning = false;
                try {
                    sleep(2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Queue<Byte> getUartRecvQueue() {
        return uartRecvQueue;
    }

    public void setUartRecvQueue(Queue<Byte> uartRecvQueue) {
        this.uartRecvQueue = uartRecvQueue;
    }

    public Uart getUart() {
        return uart;
    }

    public void setUart(Uart uart) {
        this.uart = uart;
    }
}
